<%--
  Created by IntelliJ IDEA.
  User: lenovo
  Date: 2018-05-22
  Time: 16:35
  To change this template use File | Settings | File Templates.
--%>

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>预约登记</title>
    <%@ include file="../statics/AllJavaScript.jsp" %>
    <script type="text/javascript" src="${pageContext.request.contextPath}/statics/date/Moment.js"></script>
    <script type="text/javascript"
            src="${pageContext.request.contextPath}/statics/date/bootstrap-datetimepicker.min.js"></script>
    <script type="text/javascript"
            src="${pageContext.request.contextPath}/statics/treeview/bootstrap-treeview.min.js"></script>
    <link rel="stylesheet" href="${pageContext.request.contextPath}/statics/date/bootstrap-datetimepicker.min.css"/>
    <link rel="stylesheet" href="${pageContext.request.contextPath}/statics/treeview/bootstrap-treeview.min.css"/>
    <script type="text/javascript" src="${pageContext.request.contextPath}/statics/table/rawgit-bootstrap-editable.js"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath}/statics/table/combodate.js"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath}/statics/table/bootstrap-table-editable.min.js"></script>
</head>
<body>
<div id="MyModal" class="modal fade" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title">预约详细信息</h4>
            </div>
            <div class="modal-body">
                <table class="table">
                    <h3>详细信息</h3>
                    <tr>
                        <td>姓名:<span class="name"></span></td>
                        <td>性别:<span class="sex"></span></td>
                    </tr>
                    <tr>
                        <td>出生年月: <span class="chusheng"></span></td>
                        <td>身份证号: <span class="call"></span></td>
                    </tr>
                    <tr>
                        <td>邮箱: <span class="emal"></span></td>
                        <td>电话号码: <span class="phone"></span></td>
                    </tr>
                    <tr>
                        <td>预约时间: <span class="firstDate"></span><span></span></td>
                        <td>结束时间: <span class="lastDate"></span></td>
                    </tr>
                    <tr>
                        <td>预约医生: <span class="Doctor"></span></td>
                    </tr>
                    <tr>
                        <td>备注: <span class="Remarks"></span></td>
                    </tr>
                </table>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" data-dismiss="modal">关闭</button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div>
<div id="MyModal2" class="modal fade" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <form action="" method="post" id="Addschedule">                <!--form 表单-->
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title">添加预约</h4>
                </div>
                <div class="modal-body">
                    挂号编号: <input type="text" id="guaID" onchange="GetUserInfo(this.value)" class="form-control" >
                    <p style="margin:10px" class="UserInfo">
                    </p>
                    <br/>
                    <div class="panel panel-default">
                        <div class="panel-heading">预约事项:<span style="float: right;">填充<input type="checkbox" id="tianchong"></span></div>
                        
                        <div class="panel-body">
                            <table id="yisheng"></table>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" data-dismiss="modal" id="close">关闭</button>
                    <button type="button" onclick="Submit()" class="btn btn-primary">提交</button>
                </div>
            </form>                     <!--form 结束-->
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div>
<div class="panel panel-default">
    <div class="panel-body">
        <form class="form-inline">
            <div class="form-group">
                姓名：<input id="pName" name="pName" type="text" lang="zh-CN" class="form-control" placeholder="搜索内容"/>
            </div>
            预约就诊时间：
            <div class="input-group input-daterange">
                <input id="firstDate" type="text" class="form-control">
                <span class="input-group-addon">
                    <span class="glyphicon glyphicon-calendar"></span>
                </span>
                <div class="input-group-addon">到：</div>
                <input id="secondDate" type="text" class="form-control">
                <span class="input-group-addon">
                    <span class="glyphicon glyphicon-calendar"></span>
                </span>
            </div>
            <button onclick="search()" type="button" class="btn btn-default">查询</button>
        </form>
    </div>
</div>


<button type="button" onclick="modal('add')" class="btn btn-primary">添加</button>


<table id="table"></table>
</body>
<script type="text/javascript">
    function Submit() {
        console.log(isSubmitId+"---"+isSubmitDate);
            if (row3.isEdit==1) {
                if(isSubmitId==true && isSubmitDate==true){
                    var starTime=row3.starTime;
                    var endTime=row3.endTime;
                    if(($("#tianchong").prop("checked")) &&isstarTime==true){
                        starTime=date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate()+" "+starTime;
                    }
                    if(isTime(row3.endTime,row3.starTime)){
                        alert("请检查时间")
                        return;
                    }
                    endTime=date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate()+" "+endTime;
                    var id=$("#guaID").val();
                    var remarks=row3.scheduleMatter;
                    $.ajax({
                        url:"${pageContext.request.contextPath}/make/addSchedule",
                        type:"post",
                        data:{"StarTime":starTime,"EndTime":endTime,"id":id,"NId":proId,"pId":pId,"ScheduleMatter":remarks},
                        success:function (data) {
                            if(data==true){
                                $("#close").trigger("click");
                                $("#yisheng").bootstrapTable("collapseAllRows");
                                alert("成功");
                                $("#guaID").val("");
                                 row3=null;       // 获取日程所有行数据
                                 inserrowCount=0;      // 判断是否添加过一行
                                 starTime="";           // 保存最后一次结束时间
                                 isSubmitDate=false;       // 判断时间是否可提交
                                 isSubmitId=false;         // 判断挂号编号
                                 proId=0;                      // 医生编号
                                 pId=0;                        // 患者编号
                                 isstarTime=false;          //是否修改过起始时间
                                $(".UserInfo").html("");
                            }
                        }
                    })
                }
            }else{
                alert("请检查输入的数据");
            }

    }
    function modal(stat) {
        if (stat == "add") {
            $("#guaID").val("");
            $("#MyModal2").modal();
        }
    }


  function GetUserInfo(id){
        $.ajax({
            url:"${pageContext.request.contextPath}/make/GetUserInfoByGuaId",
            type:"post",
            data:{"id":id},
            success:function(row){
                var User=$(".UserInfo");
                User.html("");
                if(row.rStat==2){
                    isSubmitId=false;
                    User.html("已预约过");
                    return;
                }else{
                    isSubmitId=true;
                }
                if(row==""){
                    isSubmitId=false;
                    User.html("未找到该挂号编号");
                    return;
                }else{
                    isSubmitId=true;
                }
                pId=row.pId;
                $("<p>姓名:"+row.pName+"</p>").appendTo(User);
                $("<p>性别:"+row.pSex+"</p>").appendTo(User);
                $("<p>手机号码:"+row.pPhone+"</p>").appendTo(User);
            }
        })
  }

    
    
    
    
    // 时间插件
    $('#firstDate').datetimepicker({
        //viewMode: 'day',
        format: 'YYYY-MM-DD'
    });
    $('#secondDate').datetimepicker({
        format: 'YYYY-MM-DD',
        useCurrent: false //Important! See issue #1075
    });
    $("#firstDate").on("dp.change", function (e) {
        $('#secondDate').data("DateTimePicker").minDate(e.date);
    });
    $("#secondDate").on("dp.change", function (e) {
        $('#firstDate').data("DateTimePicker").maxDate(e.date);
    });
    $("#BirthDate").datetimepicker({
        format:'YYYY-MM-DD',
        maxDate:(new Date())
    })

    //得到查询的参数
    function queryParams(params) {
        var temp = {  //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
            pageSize: params.pageSize,  //页面大小
            pageNumber: params.pageNumber, //页码
            pName: $("#pName").val(),
            cFirstDate: $("#firstDate").val().toString(),
            cLastDate: $("#secondDate").val().toString()
        };
        return temp;
    }

    function search() {
        var opts = $("#table").bootstrapTable('getOptions');
        var firstDate = $("#firstDate").val();
        var lastDate = $("#secondDate").val();
        var pName = $("#pName").val();
        $.ajax({
            "url": "${pageContext.request.contextPath}/make/query",
            "type": "post",
            "data": {
                "pName": pName,
                "cFirstDate": firstDate,
                "cLastDate": lastDate,
                "pageNumber": opts.pageNumber,
                "pageSize": opts.pageSize
            },
            "dataType": "json",
            "success": function (data) {
                    $("#table").bootstrapTable('load', data);
            }
        })
    }
    /**全局变量**/
    var row3;       // 获取日程所有行数据
    var inserrowCount=0;      // 判断是否添加过一行
    var starTime;           // 保存最后一次结束时间
    var isSubmitDate=false;       // 判断时间是否可提交
    var isSubmitId=false;         // 判断挂号编号
    var proId;                      // 医生编号
    var pId;                        // 患者编号
    var isstarTime;                 // 是否修改过起始时间
    function GetClickRow(row){
            row3=row;
      return;
    }

    $(function () {
       date=new Date();
        $(document).on("click","#addRowbtn",function(){
            var star2=new Date();
            star2=star2.getFullYear() + '-' + (star2.getMonth() + 1) + '-' + star2.getDate() + ' ' + star2.getHours() + ':' + star2.getMinutes() + ':' + star2.getSeconds();
            if(starTime!=null){
                starTime=new Date(starTime);
                if(starTime>date){
                    star2=starTime.getFullYear() + '-' + (starTime.getMonth() + 1) + '-' + starTime.getDate() + ' ' + starTime.getHours() + ':' + starTime.getMinutes() + ':' + starTime.getSeconds();
                }else{
                    star2=date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ' ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds();
                    starTime=star2;
                }
            }else{
                star2="09:00";
            }
            if(inserrowCount==1){
                return ;
            }else {
                var data = {};
                $('#richeng').bootstrapTable('insertRow',{
                    index:$('#richeng').bootstrapTable('getOptions').totalRows,
                    row:{"starTime":star2,"endTime":date.toLocaleString(),"scheduleMatter":"请填写日程","state":1,"isEdit":1}
                });
                inserrowCount=1;
            }

        });
        $("#table").bootstrapTable({
            url: '${pageContext.request.contextPath}/make/query',
            columns: [{
                field: 'm_id',
                title: '预约编号'
            }, {
                field: 'p_name',
                title: '患者姓名'
            }, {
                field: 'c_firstDate',
                title: '就诊时间',
                formatter: function (value, row, index) {
                    return jsonDateFormat(row.c_firstDate);
                }
            }, {
                field: 'c_lastDate',
                title: '结束时间',
                formatter:function(value, row, index) {
                    return jsonDateFormat(row.c_lastDate);
                }
            }],
            /*  responseHandler:function (res) {
                  return res.DATE;
              },*/
            onDblClickRow: function (row, $element, fidld) {
                $("#MyModal").modal();
                $(".name").html(row.p_name);
                $(".sex").html(row.p_sex);
                $(".chusheng").html(row.p_BirthDate);
                $(".call").html(row.p_cards);
                $(".emal").html(row.p_emal);
                $(".phone").html(row.p_phone)
                $(".firstDate").html(jsonDateFormat(row.c_firstDate));
                $(".lastDate").html(jsonDateFormat(row.c_lastDate));
                $(".Doctor").html(row.n_name);
                $(".Remarks").html(row.c_Remarks);
            },
            method: 'post',
            contentType: "application/x-www-form-urlencoded",
            height: 735,
            pageList: [5, 10, 15],
            pageSize: 5,
            pageNumber: 1,
            pagination: true,
            queryParamsType: '',
            queryParams: queryParams,
            sidePagination: 'server'
        });
        $("#yisheng").bootstrapTable({
                url:"${pageContext.request.contextPath}/make/GetscheduleInfo",
                height:500,
                onCollapseRow:function(index,row){
                    inserrowCount=0;
                },
                columns:[{
                    title:"医生姓名",
                    field:"n_name",
                    align:"center",
                    lineHeight:100,
                },{
                    title:"是否在职",
                    field:"n_EntryIsTrue",
                    align:"center",
                    lineHeight:100,
                    formatter:function (value,row,index) {
                        switch (row.n_EntryIsTrue){
                            case 0:
                                return "在职";
                            case 1:
                                return "不在职";
                        }
                    }
                },{
                    title:"操作",
                    formatter:function (value,row,index) {
                        return "<button type='button' class='btn btn-default' id='addRowbtn'>添加</button>";
                    }
                }],
                method: 'post',
                contentType: "application/x-www-form-urlencoded",
                pageList: [5, 10, 15],
                pageSize: 5,
                detailView:true,
                sidePagination: 'server',
                pagination: true,
                onExpandRow:function(index, row, $detail){
                  proId=row.n_id;
                  var table=$detail.html("<table id='richeng'></table>").find('table');
                  $(table).bootstrapTable({
                      url:'${pageContext.request.contextPath}/make/DataView?Pid='+proId+'',
                      /*method:"post",*/
                      /*contentType: "application/x-www-form-urlencoded",*/
                      editable:true,
                      height:350,
                      send:"never",
                      onClickRow:function(row,$element){
                          if(row.isEdit!=1){
                              return ;
                          }
                          GetClickRow(row)
                      },
                      onCollapseRow:function(index,row){
                        isstarTime=false;
                      },
                      columns:[{
                          title:"开始时间",
                          field:"starTime",
                          formatter:function (value,row,index) {
                                 return row.starTime.substring(10,16);
                          },
                          editable: {
                              title: "开始时间",
                              type: "time",
                              placement: "right",
                              format: "hh:ii",
                              validate(v) {
                                  if (row3.isEdit != 1) {
                                      isSubmitDate = false;
                                      return "只能编辑新添加的一行";
                                  }
                                  if(!($("#tianchong").prop("checked"))){
                                      isSubmitDate=false;
                                        return "未开启填充，无法修改开始时间";
                                  }
                                  if(v=="Empty"){
                                      isSubmitDate=false;
                                      return "请输入正确格式的时间";
                                  }
                                  if(!($("#tianchong").prop("checked"))){
                                      if(v<starTime){
                                          isSubmitDate=false;
                                          return "时间不能小于上一次的结束时间";
                                      }
                                  }
                                  isstarTime=true;
                                  isSubmitDate = true;
                                  starTime=v;
                              }
                          }
                      },{
                          title:"结束时间",
                          field:"endTime",
                          formatter:function (value,row,index) {
                              if(row!=null&& inserrowCount!=1){
                                      starTime=row.endTime;
                              }
                              return row.endTime.substring(10,16);
                          },
                          editable: {
                              title:"结束时间",
                              type: "time",
                              placement: "right",
                              format:"hh:ii",
                              validate(v) {
                                  var tempTime=starTime;
                                  starTime=new Date(starTime);
                                  var date=new Date();
                                  var dateStr= date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate()+' '+v;
                                  v=new Date(dateStr);
                                  if(row3.isEdit!=1){
                                      isSubmitDate=false;
                                      return "只能编辑新添加的一行";
                                  }
                                  if(!($("#tianchong").prop("checked"))){
                                      var tempTime1=new Date(tempTime);
                                      tempTime1.setMinutes(30+tempTime1.getMinutes());
                                      console.log(starTime);
                                      if(v>tempTime1){
                                          isSubmitDate=false;
                                          tempTime=new Date(tempTime);
                                          return "不能超过半个小时";
                                      }
                                  }
                                  if(v=="Empty"){
                                      isSubmitDate=false;
                                      return "请输入正确格式的时间";
                                  }
                                  if(v<starTime){
                                      isSubmitDate=false;
                                      return "时间不能小于开始时间";
                                  }
                                  isSubmitDate=true;
                                  tempTime=new Date(tempTime);
                              }
                          }
                      },{
                          title:"日程安排",
                          field:"scheduleMatter",
                          editable: {
                              title:"日程安排",
                              type: "text",
                              placement: "right",
                              validate(v) {
                                  if(row3.isEdit!=1){
                                      return "只能编辑新添加的一行";
                                  }
                              }
                          }
                      },{
                          title:"当前状态",
                          field:"state",
                          formatter:function (value,row,index) {
                              switch (row.state){
                                  case 0:
                                      return "未预约";
                                  case 1:
                                      return "已预约";
                                  case 2:
                                      return "进行中";
                                  case 3:
                                      return "已完成";
                                  case 4:
                                      return "失约";
                              }
                          }
                      }]
                  })
                  }
            }
        )
    });

    function isTime(v,v1){
        v=new Date(v);
        v1=new Date(v1);
        if(v1<v){
            isSubmitDate=false;
            return false;
        }
    }

    /*$('#addData').bind("onclick",function() {
        alert(1);
        $("#richeng").bootstrapTable("insertRow", {
            index: $("#richeng").bootstrapTable('getOptions').totalRows,
            row: {"就诊时间": "", "日程安排": ""}
        })
    })*/


   /* $('#addData').bind("onclick",function(){
        alert("1");
        $('#richeng').bootstrapTable('selectPage', 1); //Jump to the first page
        var data = {actionId: '', actionName: '',category:'', description: ''}; //define a new row data，certainly it's empty

        $('#richeng').bootstrapTable('prepend', data); //the method of prepend must defined all fields，but append needn't
        //$('#dataTable').bootstrapTable('append',data);

        $("#richeng tr:eq(1) td:eq(0)").trigger("dblclick");
        $("#richeng input")[0].focus();
    });*/


    //init editables
   /* $('.myeditable').editable({
        url: '/post' //this url will not be used for creating new user, it is only for update
    });

    //make username required
    $('#new_username').editable('option', 'validate', function(v) {
        if(!v) return 'Required field!';
    });

    //automatically show next editable
    $('.myeditable').on('save.newuser', function(){
        var that = this;
        setTimeout(function() {
            $(that).closest('tr').next().find('.myeditable').editable('show');
        }, 200);
    });*/


    function jsonDateFormat(jsonDate) {
        //json日期格式转换为正常格式
        var jsonDateStr = jsonDate.toString();//此处用到toString（）是为了让传入的值为字符串类型，目的是为了避免传入的数据类型不支持.replace（）方法
        try {
            var k = parseInt(jsonDateStr.replace("/Date(", "").replace(")/", ""), 10);
            if (k < 0)
                return null;
            var date = new Date(parseInt(jsonDateStr.replace("/Date(", "").replace(")/", ""), 10));
            var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
            var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
            var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
            var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
            var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
            var milliseconds = date.getMilliseconds();
            return date.getFullYear() + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
        }
        catch (ex) {
            return "时间格式转换错误";
        }
    }
</script>
</html>
